package cn.fl.system.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import cmm.mid.core.framework.condition.CacheRefreshPropertiesQC;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.cache.framework.constant.CacheConstant;
import cn.cmm.cache.framework.service.ICacheService;
import cn.fl.system.service.ISysPropertiesService;

/**
 * 系统属性文件服务接口实现
 * @author FUJINGRUN
 *
 */
@Service
public class SysPropertiesServiceImpl implements ISysPropertiesService {

	/**
	 * Log
	 */
	private static final Logger logger = LoggerFactory.getLogger(SysPropertiesServiceImpl.class);
	
	/**
	 * 缓存服务Bean
	 */
	@Autowired
	private ICacheService cacheService;
	
	@Override
	public Boolean refresh(CacheRefreshPropertiesQC cacheQC) throws BaseException {
		Boolean flag = true;
		try {
			BaseLogUtils.info(logger, "refresh", "刷新缓存-开始");
			initProperty();
			BaseLogUtils.info(logger, "refresh", "刷新缓存-结束");
		} catch (BaseException be) {
			BaseLogUtils.info(logger, "refresh", "刷新缓存-错误, ERROR:" + be.getMessage());
			flag = false;
		}catch (IOException e) {
			BaseLogUtils.error(logger, "refresh", "刷新缓存-错误, ERROR:" + e.getMessage());
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 初始化属性文件
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	private void initProperty() throws IOException{
		List<String> urls = getPropertyFilePath();
		Resource res = null;
		InputStream iss = null;
		Properties prop = null;
		BufferedReader bf = null;
		for (String url : urls) {
			try {
				res = new ClassPathResource(url);
				iss = res.getInputStream();
				bf = new BufferedReader(new InputStreamReader(iss, "utf-8"));
				prop = new Properties();
				prop.load(bf);
				Enumeration enKey = prop.keys();// getKeys();
				while (enKey.hasMoreElements()) {
					String key = (String) enKey.nextElement();
					String val = (String) prop.get(key);
					key = CacheConstant.CACHE_KEY_PREFIX_PROPERTIES + key;
					//this.cacheService.delete(key, CacheConstant.CACHE_OPERATION_LOCAL);
					this.cacheService.set(key, val, CacheConstant.CACHE_OPERATION_LOCAL);
				}
			} catch (Exception e) {
			BaseLogUtils.error(logger, "-", "异常", e);
			}finally {
				if(null != res){
					res = null;
				}
				
				if(null != iss){
					iss.close();
					iss = null;
				}
				
				if(null != prop){
					prop.clear();
					prop = null;
				}
			}
		}
	}
	
	
	/**
	 * 获取所有属性文件
	 * @return 属性文件路径
	 */
	private List<String> getPropertyFilePath(){
		List<String> urls = new ArrayList<String>(); 
		String rootPath = getClass().getClassLoader().getResource("/properties").getPath();
		File file = new File(rootPath);
		for (String fileName : file.list()) {
			String path = rootPath+ File.separator + fileName;
			File pathFile = new File(path);
			if(pathFile.exists() && pathFile.isFile()){
				path = path.substring(path.indexOf("properties"));
				urls.add(path);
			}else if(pathFile.exists() && pathFile.isDirectory()){
				for (String sname : pathFile.list()) {
					String lastPath = path + File.separator + sname;
					urls.add(lastPath.substring(lastPath.indexOf("properties")));
				}
			}
		}
		return urls;
	}

}
